import axios from 'axios'
import * as CryptoJS from 'crypto-js'
import { getToken } from '../util/auth'

const encryption = (params) => {
  // eslint-disable-next-line prefer-const
  let { data, type, param, key } = params
  let result = JSON.parse(JSON.stringify(data))
  if (type === 'Base64') {
    result = btoa(result['username'] + ':' + result['password'])
  } else {
    param.forEach((ele) => {
      const data = result[ele]
      key = CryptoJS.enc.Latin1.parse(key)
      // 加密
      const encrypted = CryptoJS.AES.encrypt(data, key, {
        iv: key,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.ZeroPadding
      })
      result[ele] = encrypted.toString()
    })
  }
  return result
}

const request = axios.create({
  baseURL:
    process.env.NODE_ENV === 'production'
      ? process.env.VUE_APP_AUTHAPI_HOST
      : process.env.VUE_APP_API_HOST,
  timeout: 30000 //  测试使用10秒
  // timeout: 10000 // 生产10秒
})

// 用户名密码登录 获取接口权限token
export function getAuthToken ({ username = 'anonymous', password = '123456' } = {}) {
  const data = encryption({
    data: { username, password },
    key: 'zjitdzjitd123456',
    param: ['password']
  })
  const authData = { username: 'app', password: 'app' }
  // if (username !== 'anonymous') { // 非匿名用户
  //   authData = { username: 'zlcx', password: 'zlcx' };
  // }
  const baseAuth = encryption({ data: authData, type: 'Base64' })
  const grantType = 'password'
  const scope = 'server'

  return request({
    url: '/auth/oauth/token',
    headers: {
      isToken: false,
      TENANT_ID: '1',
      Authorization: `Basic ${baseAuth}`
    },
    method: 'post',
    params: { username: data.username, password: data.password, grant_type: grantType, scope }
  })
}

// 手机号+验证码登录 获取接口权限token
export function getAuthTokenByMobile ({ mobile = '', code = '' } = {}) {
  const baseAuth = encryption({ data: { username: 'app', password: 'app' }, type: 'Base64' })
  const grantType = 'mobile'
  return request({
    url: '/auth/mobile/token/sms',
    headers: {
      isToken: false,
      TENANT_ID: '1',
      Authorization: `Basic ${baseAuth}`
    },
    method: 'post',
    params: { mobile: 'SMS@' + mobile, code, grant_type: grantType }
  })
}

// 刷新token，防止token失效
export function refreshAuthToken (token) {
  const baseAuth = encryption({ data: { username: 'app', password: 'app' }, type: 'Base64' })
  const grantType = 'refresh_token'
  return request({
    url: '/auth/oauth/token',
    headers: {
      TENANT_ID: '1',
      Authorization: `Basic ${baseAuth}`
    },
    method: 'post',
    params: { refresh_token: token, grant_type: grantType }
  })
}

// 为指定手机发送手机验证码
export function getMobileVerCode (mobile) {
  return request({
    url: '/admin/mobile/' + mobile,
    method: 'get'
  })
}
// 用户登出
export function logout () {
  return request({
    url: '/auth/token/logout',
    method: 'delete',
    headers: {
      authorization: 'Bearer ' + getToken()
    }
  })
}

// 根据token获取用户信息--主要是用于浙里办单点登录获取用户信息用
export function getUserInfoByToken (token) {
  return request({
    url: '/admin/user/info',
    method: 'get',
    headers: {
      authorization: 'Bearer ' + token
    }
  })
}

// 根据钉钉code进行登录操作
export function getAuthTokenByDingTalkCode ({ code = '' } = {}) {
  const baseAuth = encryption({ data: { username: 'app', password: 'app' }, type: 'Base64' })
  const grantType = 'mobile'
  return request({
    baseURL: process.env.VUE_APP_DD_AUTHCODE_URL,
    url: '/auth/mobile/token/sms',
    headers: {
      isToken: false,
      TENANT_ID: '1',
      Authorization: `Basic ${baseAuth}`
    },
    method: 'post',
    params: { mobile: 'ZZD@' + code, grant_type: grantType }
  })
}
